<template>
  <div style="background: #EEEEEE7F; min-height: 100vh">
    <van-nav-bar
        :title="roomInfo.subType"
        left-text="返回"
        left-arrow
        @click-left="handleBack"
    />
    <van-space direction="vertical" fill>
      <div style="margin: 8px 16px 0 16px; padding-bottom: 0;">
        <van-image
            height="200"
            :src="roomImage"
            width="100%"
            @click="showImagePreview = true"
        />
      </div>

      <CubicleSelector
          :cubicles="cubicles"
          :selectedCubicleId="selectedCubicle?.id"
          @selectCubicle="handleCubicleSelect"
      />

      <van-cell-group inset>
        <van-cell style="font-size: 18px; font-weight: bold;">
          <template #title>{{ (roomInfo.number || '') + ' ' + (roomInfo.subType || '') }}</template>
        </van-cell>
        <van-cell>
          <template #title>
            开放时段: {{ roomInfo.openTime }} - {{ roomInfo.closeTime }}
          </template>
        </van-cell>
      </van-cell-group>

      <van-cell-group inset>
        <van-cell title="预约信息" />
        <div>
          <van-cell
              :value="reservationDate"
              title="选择预约日期"
              @click="showDatePicker = true"
          />
          <van-calendar v-model:show="showDatePicker" @confirm="handleDateConfirm" />
        </div>

        <van-cell title="预约时间段" />
        <TimeSlot :timeSlots="timeSlots" @select="handleTimeSlotSelect" :selectedTimeSlotId="selectedTimeSlotId"/>
      </van-cell-group>

      <van-cell-group inset>
        <van-cell style="--van-cell-horizontal-padding: 8px">
          <van-field
              v-model="selectedReviewerName"
              is-link
              label="审核人"
              placeholder="选择审核人"
              readonly
              @click="showReviewerPicker = true"
          />
        </van-cell>
      </van-cell-group>

      <van-cell-group inset>
        <van-cell
            title="本次扣除积分"
            :value="roomPointsDisplay"
            style="--van-cell-value-color: #46afff"
        />
        <van-cell title="剩余积分" :value="userPointsDisplay" />
      </van-cell-group>

      <van-popup v-model:show="showReviewerPicker" destroy-on-close position="bottom" round>
        <van-picker
            :columns="reviewers"
            @cancel="showReviewerPicker = false"
            @confirm="handleReviewerConfirm"
        />
      </van-popup>

      <div style="width: auto; margin: 0 16px 8px 16px">
        <van-button round type="primary" style="width: 100%;" @click="submitReservation">
          立即预约
        </van-button>
      </div>
    </van-space>

    <van-image-preview v-model:show="showImagePreview" :images="[roomImage]" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { showDialog, showNotify } from "vant";
import TimeSlot from "@/apps/client/components/TimeSlot.vue";
import CubicleSelector from "@/apps/client/components/CubicleSelector.vue";
import {
  getCubicleTimeSlots,
  getRoomInfo,
  reservationCubicle,
} from "@/apps/client/utils/roomApi";
import { getUserInfo } from "@/apps/client/utils/userApi.js";
import { formatDateToYMD } from "@/apps/utils/DateUtil";
import {useRouter} from "vue-router";

const router = useRouter()
const roomId = ref<string | null>(null);
const floorName = sessionStorage.getItem("floorName");
const storedRoom = sessionStorage.getItem("selectRoom");

const roomInfo = ref<any>({
  name: null,
  number: null,
  openTime: null,
  closeTime: null,
  subType: "",
  text: "",
  cubicleCount: 0,
  pointsCost: 0,
  img: "",
});

const roomImage = ref("");
const userPointsDisplay = ref<string>("");
const roomPointsDisplay = ref<string>("");

const cubicles = ref<Array<{ id: number; name: string; selected: boolean }>>([]);
const selectedCubicle = ref<{ id: number; name: string; selected: boolean } | null>(null);

const timeSlots = ref([]);
const selectedTimeSlotId = ref<any>(null);

const reservationDate = ref(formatDateToYMD(new Date(Date.now())));

const showDatePicker = ref(false);
const showReviewerPicker = ref(false);
const showImagePreview = ref(false);

const reviewers = ref<Array<{ text: string; value: any }>>([]);
const selectedReviewer = ref<{ text: string; value: any } | null>(null);
const selectedReviewerName = ref<string>("");

// 初始化数据
onMounted(() => {
  if (!storedRoom) {
    showDialog({
      title: "错误",
      message: "未找到房间信息，请返回重试。",
    }).then(() => router.back());
    return;
  }
  const parsedRoom = JSON.parse(storedRoom);
  roomId.value = parsedRoom?.id || null;
  if (!roomId.value) {
    showDialog({
      title: "错误",
      message: "无效房间ID。",
    }).then(() => router.back());
    return;
  }
  fetchRoomInfo();
});

function fetchRoomInfo() {
  getRoomInfo(roomId.value!).then(({ code, data, msg }) => {
    if (code !== 200 ) {
      showDialog({
        title: "错误",
        message: msg,
      }).then(() => router.back());
      return;
    }
    const room = data.room;
    if (!room.available) {
      showDialog({
        title: "提示",
        message: "该房间暂未开放预约",
      }).then(() => router.back());
      return;
    }
    roomInfo.value = room;
    roomImage.value = "/api/src/img/" + room.img;
    roomPointsDisplay.value = `${room.pointsCost}积分`;
    const currentUserPoints = Number(sessionStorage.getItem("points") || 0);
    userPointsDisplay.value = `${currentUserPoints - room.pointsCost}积分`;

    setupCubicles(room.cubicleCount);
    setupReviewers(data.reviewer);

    // 默认选中第一个隔间
    if (cubicles.value.length > 0) {
      selectCubicle(cubicles.value[0]);
    }
  });
}

function setupCubicles(count: number) {
  cubicles.value = [];
  for (let i = 1; i <= count; i++) {
    cubicles.value.push({
      id: i,
      name: String(i).padStart(3, "0"),
      selected: false,
    });
  }
}

function setupReviewers(reviewerList: Array<{ id: any; name: string }>) {
  if (reviewerList.length === 0) {
    showDialog({
      title: "提示",
      message: "该房间未配置审核人, 无法提交预约",
    });
  }
  reviewers.value = reviewerList.map((r) => ({
    text: r.name,
    value: r.id,
  }));
}

function selectCubicle(cubicle: { id: number; name: string; selected: boolean }) {
  selectedCubicle.value = cubicle;
  selectedTimeSlotId.value = null;
  updateAvailableTimeSlots();
}

function updateAvailableTimeSlots() {
  if (!selectedCubicle.value) return;
  getCubicleTimeSlots({
    roomId: roomId.value!,
    cubicleNumber: selectedCubicle.value.id,
    date: reservationDate.value,
  }).then(({ data }) => {
    timeSlots.value = data;
  });
}

function handleCubicleSelect(cubicle: { id: number; name: string; selected: boolean }) {
  selectedTimeSlotId.value = null;
  selectCubicle(cubicle);
}

function handleTimeSlotSelect(slot: any) {
  selectedTimeSlotId.value = slot.id;
}

function handleDateConfirm(dateObj: Date) {
  reservationDate.value = formatDateToYMD(dateObj);
  showDatePicker.value = false;
  selectedTimeSlotId.value = null;
  updateAvailableTimeSlots();
}

function handleReviewerConfirm({ selectedValues, selectedOptions }: any) {
  showReviewerPicker.value = false;
  if (selectedOptions.length > 0) {
    selectedReviewer.value = selectedOptions[0];
    selectedReviewerName.value = selectedOptions[0].text;
  }
}

function handleBack() {
  router.back();
}

function submitReservation() {
  if (!selectedCubicle.value) {
    return showNotify({ message: "请先选择隔间" });
  }
  if (!selectedTimeSlotId.value) {
    return showNotify({ message: "请先选择时间段" });
  }
  if (!selectedReviewer.value) {
    return showNotify({ message: "请先选择审核人" });
  }
  if (!reservationDate.value) {
    return showNotify({ message: "请先选择预约日期" });
  }

  reservationCubicle({
    roomId: roomId.value!,
    cubicleNumber: selectedCubicle.value.id,
    timeSlotId: selectedTimeSlotId.value,
    reviewerId: selectedReviewer.value.value,
    date: reservationDate.value,
  }).then(({ code, msg }) => {
    if (code === 200) {
      showDialog({
        title: "预约申请提交成功",
        message:
            "请联系审核员审核",
        theme: "round-button",
        confirmButtonColor: "#1989fa",
        confirmButtonText: "我知道了",
      });
      selectedTimeSlotId.value = null;
      updateAvailableTimeSlots();
      refreshUserPoints();
    } else {
      showNotify({ message: msg });
    }
  }).catch((error) => {
    const errorMessage = error.response?.data?.msg || "预约失败，请稍后重试";
    showNotify({ message: errorMessage });
  });
}

function refreshUserPoints() {
  getUserInfo().then(({ data }) => {
    sessionStorage.setItem("points", data.points);
    userPointsDisplay.value = data.points + "积分";
  });
}
</script>

<style scoped>

</style>
